﻿using System;
using System.Collections.Generic;
using EnetaMvc.Core.Domain.Events;
using EnetaMvc.Core.Repositories;
using EnetaMvc.Infrastructure;
using NHibernate;
using NHibernate.Criterion;

namespace EnetaMvc.Data.NHibernate.Repositories
{
    public class EventRepository : BaseRepository, IEventRepository
    {
        private readonly ISession _session;

        public EventRepository(IMapperSession session)
            : base(((NHSession)session).GetCurrentSession())
        {
            _session = ((NHSession)session).GetCurrentSession();
        }

        public PagedResult<Event> ListPublicEvents(int page, int pageSize)
        {
            var criteria = _session.CreateCriteria<Event>();
            criteria.CreateCriteria("PublishState").Add(Expression.Eq("IsVisibleOnPublicSite", true));
            criteria.Add(Expression.Le("PublishStateDate", DateTime.Now));
            criteria.AddOrder(Order.Desc("Id"));

            return GetPagedResultForQuery<Event>(criteria, page, pageSize);
        }
        
        public PagedResult<Event> ListEvents(int page, int pageSize)
        {
            var criteria = _session.CreateCriteria<Event>();

            return GetPagedResultForQuery<Event>(criteria, page, pageSize);
        }

        public Event GetEventById(long id)
        {
            return _session.Get<Event>(id);
        }

        public void SaveEvent(Event instance)
        {
            SaveInTransaction(instance);
        }

        public IList<EventAttendee> GetUserAttendings(long userId)
        {
            var criteria = _session.CreateCriteria<EventAttendee>();
            criteria.CreateCriteria("User").Add(Expression.Eq("Id", userId));

            return criteria.List<EventAttendee>();
        }

        public void SaveAttendee(EventAttendee attendee)
        {
            if (attendee == null)
                return;

            SaveInTransaction(attendee);
        }


        public void DeleteAttendee(EventAttendee attendee)
        {
            if (attendee == null)
                return;

            DeleteInTransaction(attendee);
        }


        public void DeleteEvent(Event instance)
        {
            if (instance == null)
                return;

            DeleteInTransaction(instance);
        }
    }
}
